package com.eques.demo.anim

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.widget.NestedScrollView
import com.eques.base.BaseActivity
import com.eques.database.dao.DevListDao
import com.eques.database.dao.ShaowDao
import com.eques.demo.R
import com.eques.event.EventTotalThread
import com.eques.icvss.utils.ELog
import com.eques.service.DoorBellService
import com.eques.util.BaseAppApplication
import com.eques.util.Config
import com.eques.util.ObjIsEmptyUtils
import com.eques.util.StringHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.lang.ref.WeakReference
import java.util.concurrent.Executors

class AnimalSettingActivity : BaseActivity(), DialogInterface.OnClickListener {

    companion object {
        private var setStep: Int = 0
        private var ENTRO_BASE_SET_STEP: Int = 1
        private var ENTRO_BASE_DEVICE_INFO: Int = 2
        private var ENTRO_BASE_VOICE_SET: Int = 3
    }

    private var tvMainLeftTopHint: TextView? = null
    private var tvMainTitleHint: TextView? = null
    private var svBaseSet: NestedScrollView? = null
    private var constraintShowPic: ConstraintLayout? = null
    private var constraintlayoutDevice: ConstraintLayout? = null
    private var rlMainHeadParent: ConstraintLayout? = null
    private var tvMac: TextView? = null
    private var tvVersion: TextView? = null
    private var tvDbm: TextView? = null
    private var tvSmartUpgradeState: TextView? = null
    private var constraintVersion: ConstraintLayout? = null
    private var imgRotate: ImageView? = null
    private var imgOffline: ImageView? = null
    private var tvDeviceName: TextView? = null
    private var constraintlayoutVoiceSet: ConstraintLayout? = null
    private var imgOfflineDefault: ImageView? = null
    private var tvFoodTimes: TextView? = null
    private var tvSendTimes: TextView? = null
    private var tvSetTime: TextView? = null
    private var imgNotDisturb: ImageView? = null
    private var constraint_not_disturb_time: ConstraintLayout? = null
    private var tv_not_disturb_time: TextView? = null
    private var tv_mcu_state: TextView? = null
    private var tv_mcu_version: TextView? = null
    private var constraint_mcu_version: ConstraintLayout? = null

    private var lockId: String? = null
    private var devType: Int? = null
    private var devNick: String? = null
    private var mac: String? = null
    private var devUpgradeStatus = 0 // 设备升级状态
    private var isSendUpgradeMsg = false// 是否继续发送升级请求
    private var stat = -1
    private var awakenCount: Int = 0 // 唤醒次数拦截
    private var opType = -1
    private var workMode = 0
    private var mcu_num = 0
    var startTime = "22:00"
    var endTime = "8:00"
    private var power_mode = 0

    private val HANDLER_REQUEST_UPGRADE = 10
    private val REQUEST_AWAKEN = 11 // 唤醒设备
    private val HANDLER_REQUEST_OUTTIME = 12
    private val HANDLER_REQUEST_DISMISS = 13
    private val HANDLER_MCU_VERSION = 14

    private var isOfflineRemind = false//是否离线提醒

    private var voice_count: Int = 1
    private var voice_status: Int = 0
    private var brandId = 1;
    private var isShare = 0
    private var alm_mod = 0
    private var pir_stat = 0

    private lateinit var devDao: DevListDao
    private lateinit var shaowDao: ShaowDao
    private lateinit var userName: String


    private val mHandler = MyHandler(WeakReference(this))

    inner class MyHandler(val wrActivity: WeakReference<AnimalSettingActivity>) :
        Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val activity = wrActivity.get()
            when (msg.what) {
                REQUEST_AWAKEN -> {
                    if (activity!!.awakenCount <= 15) {
                        activity.awakenCount++
                        DoorBellService.icvss!!.equesT1WakeUpScreen(lockId, 2, 1)
                        mHandler.sendEmptyMessageDelayed(REQUEST_AWAKEN, 1000)
                    } else {
                        mHandler.removeMessages(REQUEST_AWAKEN)
                    }
                }

                HANDLER_REQUEST_OUTTIME -> {
                    activity!!.stopRequestProgressDialog()
                }

                HANDLER_REQUEST_DISMISS -> {
                    try {
                        stopProgressDialog()
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                }

                HANDLER_REQUEST_UPGRADE -> {
                    if (activity!!.isSendUpgradeMsg) {
                        DoorBellService.icvss!!.equesUpgradeDevice(activity.lockId)
                        sendEmptyMessageDelayed(
                            HANDLER_REQUEST_UPGRADE,
                            3000
                        )
                    }
                }

                HANDLER_MCU_VERSION -> {
                    constraint_mcu_version?.isEnabled = true
                    setMcuStatus(2)
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_animal_setting)
        EventBus.getDefault().register(this@AnimalSettingActivity)
        initView()
        initData()
        mHandler.sendEmptyMessageDelayed(HANDLER_REQUEST_DISMISS, 3 * 1000)

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRefreshEvent(event: EventTotalThread) {
        when (event.refresh) {
            Config.METHOD_MCU_UPGRADE_RESULT -> {
                stopRequestProgressDialog()
                val result = event.intMsg
                if (result == 1) {
                    constraint_mcu_version?.isEnabled = false
                    setMcuStatus(1)
                } else if (result == 2) {
                    constraint_mcu_version?.isEnabled = false
                    setMcuStatus(0)
                } else {
                    showToast(getString(R.string.t1_upgrade_failed))
                    setMcuStatus(2)
                }
            }

            Config.EVENT_METHOD_RMBDY_RESULT -> {
                // 设备删除
                val delResult: Boolean = event.isBooleanMsg
                if (delResult) {
                    finish()
                } else {
                    showToast(getString(R.string.delete_device_failed))
                }
            }

            Config.EVENT_SHADOW_SETTING_DATA_NOTIFY -> {
                getShadow()
            }

            Config.METHOD_METHOD_UPGRADE_RESULT -> {
                isSendUpgradeMsg = false
                stopRequestProgressDialog()
                updateDevUpgradeResult(event.intMsg)
            }

            Config.EVENT_E1_UPGRADE_ONLINE_NOTIFY -> {
                isSendUpgradeMsg = false
                getShadow()
            }

            Config.EVENT_DEVICE_LIST_REFRESH -> {
                CoroutineScope(Dispatchers.IO).launch {
                    val info = devDao.getBdyListEntry(userName,lockId!!)
                    if (!ObjIsEmptyUtils.isEmpty(info)) {
                        devUpgradeStatus = info.stat
                        val shaow = shaowDao.getShaowEntry(userName,lockId!!)
                        val vnum = shaow.vnum.toInt()
                        if (vnum > 0) {
                            tvVersion?.text = StringHandler.replace(
                                getString(R.string.current_device_version_settings),
                                vnum.toString()
                            )
                        }
                    }
                    setE1ProUpgradeStatus(false)

                    if (opType != -1) {
                        if (info.stat == 1) {
                            mHandler.removeMessages(REQUEST_AWAKEN)
                            if (opType == 3) {
                                opType = -1
                                stopRequestProgressDialog()
                                DoorBellService.icvss!!.updateMcu(lockId)
                            }
                            if (opType == 0) {//恢复出厂设置
                                opType = -1
                                stopRequestProgressDialog()
                                DoorBellService.icvss!!.equesSetR700Restore(lockId, 1)
                                EventBus.getDefault()
                                    .post(EventTotalThread(Config.EVENT_FINISH_ACTIVITY))
                                finish()
                            }

                            if (opType == 1) {//升级设备
                                opType = -1
                                mHandler.postDelayed(Runnable {
                                    stopRequestProgressDialog()
                                    DoorBellService.icvss!!.equesUpgradeDevice(lockId)
                                    if (isSendUpgradeMsg) {
                                        mHandler.sendEmptyMessageDelayed(
                                            HANDLER_REQUEST_UPGRADE,
                                            3000
                                        )
                                    }
                                }, (4 * 1000).toLong())
                            }
                        }
                    }
                }

            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this@AnimalSettingActivity)
    }


    override fun initView() {
        tvMainLeftTopHint = findViewById(R.id.tv_main_left_top_hint)
        tvMainTitleHint = findViewById(R.id.tv_main_title_hint)
        svBaseSet = findViewById(R.id.sv_base_set)
        constraintShowPic = findViewById(R.id.constraint_show_pic)
        constraintlayoutDevice = findViewById(R.id.constraintlayout_device)
        rlMainHeadParent = findViewById(R.id.rl_main_head_parent)
        tvFoodTimes = findViewById(R.id.tv_food_time)
        tvSendTimes = findViewById(R.id.tv_send_times)
        tvMac = findViewById(R.id.tv_mac)
        tv_mcu_state = findViewById(R.id.tv_mcu_state)
        tv_not_disturb_time = findViewById(R.id.tv_not_disturb_time)
        tvDeviceName = findViewById(R.id.tv_device_name)
        tvVersion = findViewById(R.id.tv_version)
        tv_mcu_version = findViewById(R.id.tv_mcu_version)
        tvDbm = findViewById(R.id.tv_dbm)
        constraint_not_disturb_time = findViewById(R.id.constraint_not_disturb_time)
        tvSetTime = findViewById(R.id.tv_set_time)
        imgNotDisturb = findViewById(R.id.img_not_disturb)
        constraintVersion = findViewById(R.id.constraint_version)
        tvSmartUpgradeState = findViewById(R.id.tv_smart_upgrade_state)
        imgRotate = findViewById(R.id.img_rotate)
        imgOffline = findViewById(R.id.img_offline)
        imgOfflineDefault = findViewById(R.id.img_offline_default)
        constraint_mcu_version = findViewById(R.id.constraint_mcu_version)
        constraintlayoutVoiceSet = findViewById(R.id.constraintlayout_voice_set)
        constraint_mcu_version?.isEnabled = false
        initTitleView()


    }

    override fun initData() {
        lockId = intent.getStringExtra(Config.BID)
        devType = intent.getIntExtra("devType", 0)

        devDao = BaseAppApplication.instance!!.getYkDao(this)
        shaowDao = BaseAppApplication.instance!!.getShaowDao(this)
        userName = preference.getString(Config.EQUES_USER_NAME)!!

        ELog.d("AnimalSettingActivity", "lockId..", lockId)
        getShadow()

        Executors.newSingleThreadExecutor().submit {
            getVersionInfoForServer()
        }
        isOfflineRemind = preference.getBoolean(lockId + Config.ANIMAL_IS_OFFLINE, false)
        setOfflineImgState()
        CoroutineScope(Dispatchers.IO).launch {
            val buddyInfo = devDao.getBdyListEntry(userName, lockId!!)
            devUpgradeStatus = buddyInfo.stat
        }
        setE1ProUpgradeStatus(false)
    }

    private fun showStepView() {
        when (setStep) {
            0 -> {
                tvMainTitleHint?.text = getString(R.string.xm_dev_settings)
                svBaseSet?.visibility = View.VISIBLE
                constraintShowPic?.visibility = View.GONE
                constraintlayoutDevice?.visibility = View.GONE
                constraintlayoutVoiceSet?.visibility = View.GONE
            }

            ENTRO_BASE_SET_STEP -> {
                tvMainTitleHint?.text = getString(R.string.animal_set_base)
                svBaseSet?.visibility = View.GONE
                constraintShowPic?.visibility = View.VISIBLE
            }

            ENTRO_BASE_DEVICE_INFO -> {
                setDeviceInfo()
                setE1ProUpgradeStatus(false)
                tvMainTitleHint?.text = getString(R.string.animal_device_info)
                svBaseSet?.visibility = View.GONE
                constraintlayoutDevice?.visibility = View.VISIBLE
            }

            ENTRO_BASE_VOICE_SET -> {
                svBaseSet?.visibility = View.GONE
                constraintlayoutVoiceSet?.visibility = View.VISIBLE
            }
        }
    }

    fun viewClick(view: View) {
        when (view.id) {

            R.id.constraint_mcu_version -> {
                if (power_mode == 1) {
                    if (!DoorBellService.icvss!!.equesIsLogin()) { // 判断用户是否掉线
                        userClickReconnection()
                        return
                    }
                    if (stat == 1) {
                        startProgressDialog()
                        DoorBellService.icvss!!.updateMcu(lockId)
                    } else {
                        opType = 3
                        startProgressDialog()
                        awakenCount = 0
                        mHandler.sendEmptyMessage(REQUEST_AWAKEN)
                    }
                } else {
                    showToast(getString(R.string.mcu_update_permission))
                }
            }

            R.id.constraint_not_disturb_btn -> {
                if (workMode == 0) {
                    workMode = 1
                } else {
                    workMode = 0
                }
                setShaow(2)
                setState()
            }

            R.id.constraint_not_disturb_time -> {
                val intent = Intent(this, NotDisturbActivity::class.java)
                intent.putExtra("work_mode", workMode)
                intent.putExtra("startTime", startTime)
                intent.putExtra("endTime", endTime)
                intent.putExtra(Config.BID, lockId)
                startActivity(intent)
            }

            R.id.constraint_voice_count -> {
                val intent = Intent(this, AnimalSetCountActivity::class.java)
                intent.putExtra(Config.BID, lockId)
                intent.putExtra("choose_times", voice_count)
                startActivity(intent)
            }

            R.id.constraint_voice_default -> {
                if (voice_status == 1) {
                    voice_status = 0
                } else {
                    voice_status = 1
                }
                setVoiceStatus()
                setShaow(1)
            }

            R.id.constraint_voice_set -> {
                setStep = ENTRO_BASE_VOICE_SET
                showStepView()
            }


            R.id.constraint_version -> {
                if (!DoorBellService.icvss!!.equesIsLogin()) { // 判断用户是否掉线
                    userClickReconnection()
                    return
                }
                upgradeCheck()
            }

            R.id.constraint_base_set -> {
                setStep = ENTRO_BASE_SET_STEP
                showStepView()
            }

            R.id.constraint_remind_set -> {
                isOfflineRemind = !isOfflineRemind
                preference.putBoolean(lockId + Config.ANIMAL_IS_OFFLINE, isOfflineRemind)
                setOfflineImgState()
            }


            R.id.constraint_device_info -> {
                setStep = ENTRO_BASE_DEVICE_INFO
                showStepView()
            }

            R.id.constraint_device_recovry -> {
                if (stat == Config.DEVICE_OFFLINE) {
                    ELog.showToastShort(this@AnimalSettingActivity, R.string.vl0_state_hint)
                    return
                }
                if (stat == 1) {
                    DoorBellService.icvss!!.equesSetR700Restore(lockId, 1)
                    EventBus.getDefault()
                        .post(EventTotalThread(Config.EVENT_FINISH_ACTIVITY))
                    finish()
                } else {
                    startProgressDialog()
                    awakenCount = 0
                    opType = 0
                    mHandler.sendEmptyMessage(REQUEST_AWAKEN)
                }
            }

            R.id.tv_del_dev -> {
                preference.putBoolean(
                    Config.IS_DEL_DEV,
                    true
                )
                DoorBellService.icvss!!.equesDelDevice(lockId)
            }
        }

    }

    private fun setShaow(commad: Int) {
        val jsonObject = JSONObject()
        try {
            if (commad == 1) {
                jsonObject.put("voice_status", voice_status.toString())
            }
            if (commad == 2) {
                jsonObject.put("disturb_status", workMode.toString())
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        Executors.newSingleThreadExecutor().submit {
            setInfo(jsonObject.toString(), lockId!!)
        }
    }


    /**
     * 设置头部昵称
     */
    private fun setTitleNick() {
        if (TextUtils.isEmpty(devNick)) {
            tvDeviceName!!.setText(R.string.animal)
        } else {
            tvDeviceName!!.text = devNick
        }
    }

    /**
     * 初始化头部标题栏
     */
    private fun initTitleView() {
        tvMainLeftTopHint!!.visibility = View.VISIBLE
        tvMainLeftTopHint?.setCompoundDrawablesWithIntrinsicBounds(
            resources.getDrawable(R.mipmap.ic_invitation_menu),
            null,
            null,
            null
        )
        tvMainLeftTopHint?.setOnClickListener {
            if (setStep != 0) {
                setStep = 0
                showStepView()
            } else {
                finish()
            }
        }
        rlMainHeadParent!!.setBackgroundColor(Color.WHITE)
        tvMainTitleHint?.visibility = View.VISIBLE
        tvMainTitleHint?.text = getString(R.string.xm_dev_settings)
        tvMainTitleHint?.setTextColor(resources.getColor(R.color.common_color_333333))
    }


    private fun setOfflineImgState() {
        if (isOfflineRemind) {
            imgOffline?.setImageResource(R.mipmap.button_switch_on)
        } else {
            imgOffline?.setImageResource(R.mipmap.button_switch_off)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun getShadow() {
        CoroutineScope(Dispatchers.IO).launch {
            val shaow = shaowDao.getShaowEntry(userName, lockId!!)
            val info = devDao.getBdyListEntry(userName, lockId!!)
            if (!ObjIsEmptyUtils.isEmpty(shaow)) {
                val wifiName = shaow.wifi_ssid
                //                    // 网络信号质量
                val wifiRssi = shaow.wifi_level
                alm_mod = shaow.alm_mod.toInt()
                pir_stat = shaow.alarm_enable.toInt()
                voice_count = shaow.voice_count.toInt()
                voice_status = shaow.voice_status.toInt()
                if ("" != shaow.usb_vnum) {
                    mcu_num = shaow.usb_vnum.toInt()
                }
                tvSendTimes?.text = voice_count.toString() + getString(R.string.animal_count)
                workMode = shaow.disturb_status.toInt()
                setState()
                startTime = shaow.disturb_start_time.toString()
                endTime = shaow.disturb_end_time.toString()
                power_mode = shaow.power_mode.toInt()
                brandId = shaow.brand_id.toInt()
            }
            if (!ObjIsEmptyUtils.isEmpty(info)) {
                devNick = info.nick
                mac = info.name
                stat = info.stat
                isShare = info.is_share


                setVoiceStatus()
            }
        }

        setTitleNick()

        tvSetTime?.text = startTime + "-" + endTime
        tv_mcu_version?.text = StringHandler.replace(
            getString(R.string.current_device_version_settings),
            mcu_num.toString()
        )
    }

    private fun setState() {
        if (workMode == 1) {
            imgNotDisturb?.setImageResource((R.mipmap.button_switch_on))
            constraint_not_disturb_time?.visibility = View.VISIBLE
            tv_not_disturb_time?.visibility = View.VISIBLE
        } else {
            imgNotDisturb?.setImageResource((R.mipmap.button_switch_off))
            constraint_not_disturb_time?.visibility = View.GONE
            tv_not_disturb_time?.visibility = View.GONE
        }
    }

    private fun setVoiceStatus() {
        if (voice_status == 0) {
            imgOfflineDefault?.setImageResource(R.mipmap.button_switch_off)
        } else {
            imgOfflineDefault?.setImageResource(R.mipmap.button_switch_on)
        }
    }

    /**
     * 设置设备mac
     */
    @SuppressLint("SetTextI18n")
    private fun setDeviceInfo() {
        CoroutineScope(Dispatchers.IO).launch {
            var details =shaowDao.getShaowEntry(userName,lockId!!)
            if (!ObjIsEmptyUtils.isEmpty(details)) {
                if (!TextUtils.isEmpty(mac)) {
                    tvMac?.text = mac
                }
                val vnum = details.vnum.toInt()
                if (vnum > 0) {
                    tvVersion?.text = StringHandler.replace(
                        getString(R.string.current_device_version_settings),
                        vnum.toString()
                    )
                }
                val dbm = details.wifi_rssi.toInt()
                if (dbm > -40) {
                    tvDbm?.text = details.wifi_ssid + "（强" + dbm + "dbm)"
                } else if (dbm >= -60) {
                    tvDbm?.text = details.wifi_ssid + " （一般" + dbm + "dbm)"
                } else {
                    tvDbm?.text = details.wifi_ssid + " （弱" + dbm + "dbm)"
                }

            }
        }

    }

    private fun setMcuStatus(status: Int) {
        var state = status
        if (devUpgradeStatus == 2 || devUpgradeStatus == 1) {
            state = 0
        }
        when (state) {
            1 -> {
                tv_mcu_state?.setText(R.string.e1_upgrade_waiting_hint)
                tv_mcu_state?.setTextColor(resources.getColor(R.color.pir_sensitivity_hint))
                tv_mcu_state?.setBackgroundResource(R.drawable.d1_upgrade_tv_style)
            }

            2 -> {
                tv_mcu_state?.setText(R.string.new_version_upgrade)
                tv_mcu_state?.setTextColor(resources.getColor(R.color.pir_sensitivity_hint))
                tv_mcu_state?.setBackgroundResource(R.drawable.d1_upgrade_tv_style)
            }

            0 -> {
                tv_mcu_state?.setText(R.string.check_version_prompt_one)
                tv_mcu_state?.setTextColor(resources.getColor(R.color.settings_right_tv_color_two))
                tv_mcu_state?.setBackgroundResource(R.drawable.def_transp_bg)
            }
        }
    }


    /**
     * 设备升级状态
     *
     * @param isOperationUpgrade 是否操作升级
     */
    private fun setE1ProUpgradeStatus(isOperationUpgrade: Boolean) {
        when (devUpgradeStatus) {
            Config.DEVICE_NEED_UPDATE -> {
                tvSmartUpgradeState?.setText(R.string.e1_upgrade_waiting_hint)
                tvSmartUpgradeState?.setTextColor(resources.getColor(R.color.pir_sensitivity_hint))
                tvSmartUpgradeState?.setBackgroundResource(R.drawable.d1_upgrade_tv_style)
            }

            Config.DEVICE_IS_UPDATING -> {
                tvSmartUpgradeState?.setText(R.string.new_version_upgrade)
                tvSmartUpgradeState?.setTextColor(resources.getColor(R.color.pir_sensitivity_hint))
                tvSmartUpgradeState?.setBackgroundResource(R.drawable.d1_upgrade_tv_style)
            }

            else -> {
                tvSmartUpgradeState?.setText(R.string.check_version_prompt_one)
                tvSmartUpgradeState?.setTextColor(resources.getColor(R.color.settings_right_tv_color_two))
                tvSmartUpgradeState?.setBackgroundResource(R.drawable.def_transp_bg)
            }
        }
    }

    /**
     * 设备升级检测
     */
    fun upgradeCheck() {
        if (stat == Config.DEVICE_OFFLINE) {
            ELog.showToastShort(
                this@AnimalSettingActivity,
                R.string.vl0_state_hint
            )
            return
        } else {
            if (devUpgradeStatus == Config.NOT_NEED_UPDATE) {
                ELog.showToastShort(
                    this@AnimalSettingActivity,
                    R.string.check_version_prompt_one
                )
                return
            }
            if (devUpgradeStatus == Config.IS_UPDATING) {
                ELog.showToastShort(
                    this@AnimalSettingActivity,
                    R.string.device_updating
                )
                return
            }
            if (stat == 1) {
                opType = -1
                startProgressDialog()
                DoorBellService.icvss!!.equesUpgradeDevice(lockId)
                if (isSendUpgradeMsg) {
                    mHandler.sendEmptyMessageDelayed(
                        HANDLER_REQUEST_UPGRADE,
                        3000
                    )
                }
            } else {
                startProgressDialog()
                awakenCount = 0
                mHandler.sendEmptyMessage(REQUEST_AWAKEN)
            }
        }
    }

    /**
     * 更新设备升级结果返回
     *
     * @param resultCode
     */
    fun updateDevUpgradeResult(resultCode: Int) {
        when (resultCode) {
            Config.DEVICE_UPDATE_FAILED_BATTERY_LOW -> ELog.showToastShort(
                this@AnimalSettingActivity,
                getString(R.string.upgrade_failed_battery_low)
            )

            Config.DEVICE_UPDATE_FAILED_MEMORY_LOW -> ELog.showToastShort(
                this@AnimalSettingActivity,
                getString(R.string.upgrade_failed_storage_Low)
            )

            Config.DEVICE_UPDATE_FAILED_NO_SDCARD -> ELog.showToastShort(
                this@AnimalSettingActivity,
                getString(R.string.upgrade_no_sd_card_hint)
            )

            else -> {
                devUpgradeStatus = resultCode
                setE1ProUpgradeStatus(true)
                ELog.showToastLong(
                    this@AnimalSettingActivity,
                    getString(R.string.e1_update_warning)
                )
            }
        }
    }


    /**
     * 开始请求等待
     */
    fun startProgressDialog() {
        createProgressDialog(this, Config.PROGRESS_ERROR_CODE, false)
        mHandler.sendEmptyMessageDelayed(HANDLER_REQUEST_OUTTIME, 6000)
    }

    /**
     * 结束请求等待
     */
    fun stopRequestProgressDialog() {
        stopProgressDialog()
        mHandler.removeMessages(HANDLER_REQUEST_OUTTIME)
    }


    private fun getVersionInfoForServer() {
        var serverIp = preference.getString(Config.MAIN_ADDRESS)
        val token = preference.getString(Config.EQUES_USER_TOKEN)
        var uid = preference.getString(Config.EQUES_USER_UID)
        val url = Config.getQueryMcuVer(
            serverIp!!,
            uid!!,
            token!!,
            devType.toString(),
            brandId.toString(),
            mcu_num.toString()
        )
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(url!!)
            .build()
        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) throw IOException("Unexpected code $response")
            var jsonObject = response.body?.string()?.let { JSONObject(it) }
            try {
                var code = jsonObject?.get("code")
                if (code == 0) {
                    var data: JSONObject = jsonObject?.optJSONObject("data")!!
                    var remoteupg = data.optInt("remoteupg")
                    if (remoteupg == 1) {
                        val msg = Message.obtain()
                        msg.obj = data.optInt("version")
                        msg.what = HANDLER_MCU_VERSION
                        mHandler.sendMessage(msg)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onClick(p0: DialogInterface?, p1: Int) {
    }

}


